import base64
import pickle

from django.conf import settings
from django.shortcuts import render

# Create your views here.
# 判断用户是否存在
from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework import status
from rest_framework.generics import CreateAPIView, GenericAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializers
from users import serializers
from users.models import User
from users.serializers import CreateUserSerializer, AddUserBrowsingHistorySerializer
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


class UserNameCountView(GenericAPIView):
    """
    用户名数量
    """
    def get(self, request, username):
        """
        获取指定用户名数量
        :param request:
        :param username:
        :return:
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count,
        }

        return Response(data)

        # return Response(
        #     {
        #         'username': username,
        #         'count': count
        #     }
        # )


# 判断手机好是否已注册过
class MobileCountView(GenericAPIView):
    """
    手机号数量
    """
    def get(self, request, mobile):
        """
        获取指定手机号数量
        :param request:
        :param mobile:
        :return:
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count,
        }

        return Response(data)


class UserView(CreateAPIView):
    """
    用户注册
    传入参数
     username, password, password2, sms_code, mobile, allow
    """
    serializer_class = CreateUserSerializer


# 用户信息展示
class UserDetailView(RetrieveAPIView):
    """
    用户详情
    """
    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    """
    保存用户邮箱
    """
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailSerializer

    def get_object(self, *args, **kwargs):
        return self.request.user


# 邮箱认证成功后返回
class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        # 获取ｔｏｋｅｎ
        token = request.query_params.get('token')

        # 解密ｔｏｋｅｎ
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return Response({'message': "缺少ｔｏｋｅｎ"}, status=status.HTTP_400_BAD_REQUEST)

        # 验证ｔｏｋｅｎ
        if not data:
            return Response({'message': "ｔｏｋｅｎ失效"}, status=status.HTTP_400_BAD_REQUEST)

        id = data['id']
        username = data['username']

        # 验证用户
        try:
            user = User.objects.get(id=id, username=username)
        except:
            return Response({'message': "用户不存在"}, status=status.HTTP_400_BAD_REQUEST)

        # 更新状态
        user.email_active = True
        user.save()
        return Response({'message': 'OK'})


# 新增用户地址
# class AddressView(CreateAPIView, UpdateAPIView, GenericViewSet):
class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

#     ＧＥＴ／ａｄｄｒｅｓｓ
    def list(self, request, *args, **kwargs):
        """
        用户地址数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

#     POST/address/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # 检查用户地址是否达到上限
        count = request.user.addresses.count()
        if count > 20:
            return Response({'message': '保存地址数量达上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete/address/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put/address/pk/status
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        :param request:
        :param pk:
        :return:
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'})

    # put/address/pk/title
    # 需求请求体参数ｔｉｔｌｅ
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        :param request:
        :param pk:
        :return:
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# 浏览历史记录
class UserBrowsingHistoryView(CreateAPIView):

    serializer_class = AddUserBrowsingHistorySerializer
    # 权限设置
    permission_classes = [IsAuthenticated]

    def get(self, request):

        user = request.user

        # 建立链接
        conn = get_redis_connection('history')

        # 数据获取
        sku_id_list = conn.lrange('history_%s' % user.id, 0, 9)  # 获取的数据类型为ｂｙｔｅｓ类型
                                                                    # ｂｙｔｅｓ类型能和ｉｎｔ类型进行比较，但不能和ｓｔｒ类型比较

        # 查询数据
        sku_list = []
        for sku_id in sku_id_list:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 序列化返回
        ser = SKUSerializers(sku_list, many=True)

        return Response(ser.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户认证
    """
    def post(self, request, *args, **kwargs):

        # 调用父类的方法，获取drf jwt扩展默认的认证用户处理结果
        response = super().post(request, *args, **kwargs)

        # 仿照drf jwt扩展对于用户登录的认证方式，判断用户是否认证登录成功
        # 如果用户登录认证成功，则合并购物车
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 用户存在
            user = serializer.object.get('user')
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)

        return response

# class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
#     """
#     用户地址新增与修改
#     """
#     serializer_class = serializers.UserAddressSerializer
#     permissions = [IsAuthenticated]
#
#     def get_queryset(self):
#         return self.request.user.addresses.filter(is_deleted=False)
#
#     # GET /addresses/
#     def list(self, request, *args, **kwargs):
#         """
#         用户地址列表数据
#         """
#         queryset = self.get_queryset()
#         serializer = self.get_serializer(queryset, many=True)
#         user = self.request.user
#         return Response({
#             'user_id': user.id,
#             'default_address_id': user.default_address_id,
#             'limit': 20,
#             # 'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
#             'addresses': serializer.data,
#         })
#
#     # POST /addresses/
#     def create(self, request, *args, **kwargs):
#         """
#         保存用户地址数据
#         """
#         # 检查用户地址数据数目不能超过上限
#         count = request.user.addresses.count()
#         # if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
#         if count >= 20:
#             return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)
#
#         return super().create(request, *args, **kwargs)
#
#     # delete /addresses/<pk>/
#     def destroy(self, request, *args, **kwargs):
#         """
#         处理删除
#         """
#         address = self.get_object()
#
#         # 进行逻辑删除
#         address.is_deleted = True
#         address.save()
#
#         return Response(status=status.HTTP_204_NO_CONTENT)
#
#     # put /addresses/pk/status/
#     @action(methods=['put'], detail=True)
#     def status(self, request, pk=None):
#         """
#         设置默认地址
#         """
#         address = self.get_object()
#         request.user.default_address = address
#         request.user.save()
#         return Response({'message': 'OK'}, status=status.HTTP_200_OK)
#
#     # put /addresses/pk/title/
#     # 需要请求体参数 title
#     @action(methods=['put'], detail=True)
#     def title(self, request, pk=None):
#         """
#         修改标题
#         """
#         address = self.get_object()
#         serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response(serializer.data)
""""""
# class VerifyEmailView(APIView):
#
#     def get(self, request):
#
#         # 获取前端token值
#         token = request.query_params.get('token')
#
#         # 解密token
#         tjs = TJS(settings.SECRET_KEY, 300)
#         try:
#             data = tjs.loads(token)
#         except:
#             return Response({'errors': '错误的token'}, status=401)
#
#         if not data:
#             return Response({'errors': 'token失效'}, status=401)
#         # 获取解密后的值
#         id = data['id']
#         username = data['username']
#
#         # 查询用户
#         try:
#             user=User.objects.get(id=id,username=username)
#         except:
#             return Response({'errors': '用户不存在'}, status=401)
#
#         # 更新激活状态
#         user.email_active=True
#         user.save()
#
#         # 结果返回
#         return Response({'message':'ok'})

""""""

# from django.shortcuts import render
# from rest_framework.generics import RetrieveAPIView, GenericAPIView, CreateAPIView
# from rest_framework.response import Response
# from users.models import User
#
# # Create your views here.
# from users.serializers import UserSerializer
#
#
# class UserNmaeView(GenericAPIView):
#     def get(self, request, username):
#         # 用户名数量查询
#         count = User.objects.filter(username=username).count()
#
#         # 返回数量
#         return Response(
#             {
#                 'username': username,
#                 'count': count
#             }
#         )
#
#
# class MobileView(GenericAPIView):
#     def get(self, request, mobile):
#         # 手机号数量查询
#         count = User.objects.filter(mobile=mobile).count()
#
#         # 返回数量
#         return Response(
#             {
#                 'mobile': mobile,
#                 'count': count
#             }
#         )
#
#
# class UserView(CreateAPIView):
#     serializer_class = UserSerializer
